<template>
  <div class="user-profile">
    <!-- 头部用户信息 -->
    <div class="user-header">
      <div class="user-avatar">
        <img :src="userAvatar" alt="头像" @error="handleAvatarError">
      </div>
      <div class="user-info">
        <h3>{{ displayName }}</h3>
        <p>{{ displayPhone }}</p>
        <p>{{ displayEmail }}</p>
        <!-- VIP等级显示 -->
        <div class="vip-display" v-if="vipLevel">
          <span class="vip-badge" :class="'vip-level-' + vipLevel.level">
            <i class="fas fa-crown"></i>
            <span>{{ vipLevel.name }}</span>
          </span>
          <span class="vip-privilege">
            透支限额×{{ vipLevel.overdraftMultiplier }}，
            利息{{ (vipLevel.interestDiscount * 100).toFixed(0) }}%
          </span>
        </div>
        <div class="vip-display" v-else>
          <span class="vip-badge vip-level-0">
            <i class="fas fa-user"></i>
            <span>普通用户</span>
          </span>
        </div>
      </div>
    </div>

    <!-- 功能菜单 -->
    <div class="menu-list">
      <!-- 个人信息 -->
      <div class="menu-item" @click="toPersonalInfo">
        <i class="fas fa-user-edit"></i>
        <span>个人信息</span>
        <i class="fas fa-chevron-right"></i>
      </div>

      <!-- 修改密码 -->
      <div class="menu-item" @click="toChangePassword">
        <i class="fas fa-lock"></i>
        <span>修改密码</span>
        <i class="fas fa-chevron-right"></i>
      </div>

      <!-- 我的订单 -->
      <div class="menu-item" @click="toOrderList">
        <i class="fas fa-file-alt"></i>
        <span>我的订单</span>
        <i class="fas fa-chevron-right"></i>
      </div>

      <!-- 我的钱包 -->
      <div class="menu-item" @click="toWallet">
        <i class="fas fa-wallet"></i>
        <span>我的钱包</span>
        <i class="fas fa-chevron-right"></i>
      </div>

      <!-- 我的地址 -->
      <div class="menu-item" @click="toAddressManagement">
        <i class="fas fa-map-marker-alt"></i>
        <span>我的地址</span>
        <i class="fas fa-chevron-right"></i>
      </div>

      <!-- VIP规则说明 -->
      <div class="menu-item" @click="showVipRules">
        <i class="fas fa-crown"></i>
        <span>VIP规则说明</span>
        <i class="fas fa-chevron-right"></i>
      </div>

      <!-- 成为商家 -->
      <div class="menu-item" @click="toBusinessApplication">
        <i class="fas fa-store"></i>
        <span>成为商家</span>
        <i class="fas fa-chevron-right"></i>
      </div>

      <!-- 退出登录 -->
      <div class="menu-item logout" @click="handleLogout">
        <i class="fas fa-sign-out-alt"></i>
        <span>退出登录</span>
      </div>
    </div>

    <!-- VIP规则说明对话框 -->
    <div class="dialog-overlay" v-if="showVipDialog" @click.self="showVipDialog = false">
      <div class="vip-rules-dialog" @click.stop>
        <div class="dialog-header">
          <h3>VIP等级规则</h3>
          <button class="close-btn" @click="showVipDialog = false">
            <i class="fas fa-times"></i>
          </button>
        </div>
        <div class="dialog-body">
          <div class="vip-rules-content">
            <div class="rule-section">
              <h4>升级条件</h4>
              <p class="rule-intro">VIP等级根据累计消费和累计充值金额自动升级</p>
              <div class="vip-levels-list">
                <div class="vip-level-item" v-for="level in vipRulesData" :key="level.level">
                  <div class="level-header">
                    <span class="vip-badge" :class="'vip-level-' + level.level">
                      <i class="fas fa-crown"></i>
                      <span>{{ level.name }}</span>
                    </span>
                  </div>
                  <div class="level-requirements">
                    <div class="requirement">
                      <i class="fas fa-shopping-cart"></i>
                      <span>累计消费满 <strong>{{ level.minConsumption }}元</strong></span>
                    </div>
                    <div class="requirement">
                      <i class="fas fa-wallet"></i>
                      <span>累计充值满 <strong>{{ level.minRecharge }}元</strong></span>
                    </div>
                  </div>
                  <div class="level-privileges">
                    <h5>等级特权：</h5>
                    <div class="privilege-item">
                      <i class="fas fa-coins"></i>
                      <span>透支限额×{{ level.overdraftMultiplier }}</span>
                    </div>
                    <div class="privilege-item">
                      <i class="fas fa-percentage"></i>
                      <span>利息{{ level.interestDiscount * 100 }}%</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <div class="rule-section">
              <h4>升级说明</h4>
              <ul class="rule-notes">
                <li>系统根据您的累计消费和充值金额自动计算VIP等级</li>
                <li>累计消费包括所有订单支付金额（不含退款）</li>
                <li>累计充值包括所有成功充值的金额（不含奖励）</li>
              </ul>
            </div>
          </div>
        </div>
        <div class="dialog-footer">
          <button class="confirm-btn" @click="showVipDialog = false">我知道了</button>
        </div>
      </div>
    </div>

    <!--  底部菜单-->
    <Footer></Footer>

  </div>
</template>

<script setup>
import {ref, onMounted, computed, onActivated} from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { userAPI } from '@/api/user.js'
import Footer from "@/components/Footer.vue";

const router = useRouter()
const authStore = useAuthStore()

// 用户信息
const userInfo = ref({
  firstName: '',
  lastName: '',
  phone: '',
  email: '',
  username: '',
  photo: '',
  vipLevel: '',
  vipLevelValue: 0,
  totalConsumption: 0,
  totalRecharge: 0
})
const avatarError = ref(false)
const vipLevel = ref(null)  // 当前VIP等级详情
const showVipDialog = ref(false)  // 是否显示VIP规则对话框

// VIP规则数据
const vipRulesData = ref([
  {
    level: 1,
    name: '青铜',
    minConsumption: 500,
    minRecharge: 300,
    overdraftMultiplier: 1.2,
    interestDiscount: 0.95
  },
  {
    level: 2,
    name: '白银',
    minConsumption: 2000,
    minRecharge: 1000,
    overdraftMultiplier: 1.5,
    interestDiscount: 0.90
  },
  {
    level: 3,
    name: '黄金',
    minConsumption: 5000,
    minRecharge: 3000,
    overdraftMultiplier: 2.0,
    interestDiscount: 0.85
  },
  {
    level: 4,
    name: '铂金',
    minConsumption: 10000,
    minRecharge: 5000,
    overdraftMultiplier: 3.0,
    interestDiscount: 0.80
  },
  {
    level: 5,
    name: '钻石',
    minConsumption: 20000,
    minRecharge: 10000,
    overdraftMultiplier: 5.0,
    interestDiscount: 0.70
  }
])

// 计算属性：用户头像
const userAvatar = computed(() => {
  if (avatarError.value || !userInfo.value.photo) {
    return require('@/assets/userImg/userImg.png')
  }
  return userInfo.value.photo
})

// 计算属性：全名
const fullName = computed(() => {
  if (userInfo.value.firstName && userInfo.value.lastName) {
    return userInfo.value.lastName + userInfo.value.firstName
  } else if (userInfo.value.firstName) {
    return userInfo.value.firstName
  } else if (userInfo.value.lastName) {
    return userInfo.value.lastName
  } else {
    return '未设置昵称'
  }
})

// 页面加载时获取用户信息
onMounted(async () => {
  await loadUserInfo()
})

// 当页面被激活时重新加载数据（解决缓存问题）
onActivated(async () => {
  await loadUserInfo()
})

// 头像加载失败处理
const handleAvatarError = () => {
  avatarError.value = true
}

// 加载用户信息
const loadUserInfo = async () => {
  try {
    const response = await userAPI.information()
    console.log('完整响应:', response)

    // 简化数据处理逻辑
    let data = null

    // 根据实际响应结构调整
    if (response.data && response.data.success === true && response.data.data) {
      // 如果后端返回 { success: true, code: 'OK', data: {...}, message: null }
      data = response.data.data
    } else if (response.data && response.data.id) {
      // 如果后端直接返回 Person 对象
      data = response.data
    } else {
      // 其他情况
      data = response.data
    }

    console.log('提取的用户数据:', data)

    if (data) {
      userInfo.value = data
      // 直接从用户信息构建VIP等级显示
      if (userInfo.value.vipLevel && userInfo.value.vipLevelValue > 0) {
        vipLevel.value = {
          name: userInfo.value.vipLevel,
          level: userInfo.value.vipLevelValue,
          overdraftMultiplier: 1.0,  // 默认值，可根据需要调整
          interestDiscount: 1.0      // 默认值，可根据需要调整
        }
      }
    } else {
      console.error('未获取到用户数据')
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
  }
}

// 加载VIP等级信息（已集成到loadUserInfo中）
// const loadVipLevel = async () => {
//   // 该方法已废弃，VIP信息现在直接在loadUserInfo中处理
// }

// 跳转到个人信息页面
const toPersonalInfo = () => {
  console.log('跳转到个人信息页面')
  router.push('/personalInfo')
}

// 跳转到修改密码页面
const toChangePassword = () => {
  console.log('跳转到修改密码页面')
  router.push('/changePassword')
}

// 跳转到订单列表
const toOrderList = () => {
  console.log('跳转到订单列表')
  router.push('/orderList')
}

// 跳转到钱包
const toWallet = () => {
  console.log('跳转到钱包')
  router.push('/wallet')
}

// 跳转到地址管理
const toAddressManagement = () => {
  console.log('跳转到地址管理')
  router.push('/userAddress')
}

// 跳转到开店申请
const toBusinessApplication = () => {
  console.log('跳转到开店申请')
  router.push('/businessApplicationList')
}

// 显示VIP规则说明
const showVipRules = () => {
  showVipDialog.value = true
}

// 退出登录
const handleLogout = () => {
  if (confirm('确定要退出登录吗？')) {
    authStore.logout()
    router.push('/login')
  }
}

  const displayName = computed(() => {
    const user = userInfo.value
    if (user.firstName && user.lastName) {
      return user.lastName + user.firstName
    } else if (user.firstName) {
      return user.firstName
    } else if (user.lastName) {
      return user.lastName
    } else if (user.username) {
      return user.username
    } else {
      return '未设置昵称'
    }
  })

  const displayPhone = computed(() => {
    return userInfo.value.phone ? userInfo.value.phone : '未绑定手机'
  })

  const displayEmail = computed(() => {
    return userInfo.value.email ? userInfo.value.email : '未绑定邮箱'
  })

</script>



<style scoped>
.user-profile {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 14vw; /* 为底部导航留出空间 */
}

.user-header {
  background: linear-gradient(135deg, #ff6b6b, #ee5a24);
  color: white;
  padding: 6vw 4vw;
  display: flex;
  align-items: center;
}

.user-avatar {
  width: 20vw;
  height: 20vw;
  border-radius: 50%;
  overflow: hidden;
  margin-right: 4vw;
  border: 3px solid rgba(255, 255, 255, 0.3);
}

.user-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.user-info h3 {
  font-size: 5vw;
  margin-bottom: 1vw;
}

.user-info p {
  font-size: 3.5vw;
  opacity: 0.9;
}

.vip-display {
  margin-top: 1.5vw;
}

.vip-badge {
  display: inline-flex;
  align-items: center;
  gap: 0.5vw;
  padding: 0.5vw 1.5vw;
  border-radius: 2vw;
  font-size: 3vw;
  font-weight: 600;
  color: white;
  margin-bottom: 0.5vw;
}

.vip-level-0 {
  background: #95a5a6;
}

.vip-level-1 {
  background: linear-gradient(135deg, #cd7f32, #b8732d);
}

.vip-level-2 {
  background: linear-gradient(135deg, #c0c0c0, #a8a8a8);
}

.vip-level-3 {
  background: linear-gradient(135deg, #ffd700, #e5c100);
  color: #333;
}

.vip-level-4 {
  background: linear-gradient(135deg, #e5e4e2, #c0c0c0);
  color: #333;
}

.vip-level-5 {
  background: linear-gradient(135deg, #b9f2ff, #89d4f0);
  color: #333;
}

.vip-privilege {
  display: block;
  font-size: 2.5vw;
  opacity: 0.8;
  margin-top: 0.5vw;
}

.menu-list {
  background: white;
  margin-top: 3vw;
}

.menu-item {
  display: flex;
  align-items: center;
  padding: 4vw;
  border-bottom: 1px solid #f0f0f0;
  font-size: 4vw;
  cursor: pointer;
  transition: background-color 0.3s;
}

.menu-item:hover {
  background-color: #f9f9f9;
}

.menu-item i:first-child {
  width: 6vw;
  text-align: center;
  margin-right: 3vw;
  color: #666;
}

.menu-item span {
  flex: 1;
  color: #333;
}

.menu-item i:last-child {
  color: #ccc;
  font-size: 3.5vw;
}

.menu-item.logout {
  color: #ff4757;
  margin-top: 3vw;
}

.menu-item.logout i:first-child {
  color: #ff4757;
}

.menu-item.logout span {
  color: #ff4757;
}

/****************** VIP规则对话框部分 ******************/
.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.vip-rules-dialog {
  background-color: white;
  border-radius: 2vw;
  width: 90%;
  max-height: 80vh;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.vip-rules-dialog .dialog-header {
  padding: 4vw;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.vip-rules-dialog .dialog-header h3 {
  font-size: 5vw;
  color: #333;
  margin: 0;
}

.vip-rules-dialog .close-btn {
  background: none;
  border: none;
  font-size: 5vw;
  color: #999;
  cursor: pointer;
}

.vip-rules-dialog .dialog-body {
  flex: 1;
  overflow-y: auto;
  padding: 4vw;
}

.vip-rules-content {
  color: #333;
}

.rule-section {
  margin-bottom: 5vw;
}

.rule-section h4 {
  font-size: 4.5vw;
  margin-bottom: 2vw;
  color: #333;
}

.rule-section h5 {
  font-size: 3.5vw;
  margin-bottom: 1.5vw;
  color: #666;
}

.rule-intro {
  font-size: 3.5vw;
  color: #666;
  margin-bottom: 3vw;
}

.vip-levels-list {
  display: flex;
  flex-direction: column;
  gap: 3vw;
}

.vip-level-item {
  padding: 3vw;
  background-color: #f9f9f9;
  border-radius: 1.5vw;
}

.level-header {
  margin-bottom: 2vw;
}

.level-requirements {
  margin-bottom: 2vw;
}

.requirement {
  display: flex;
  align-items: center;
  font-size: 3.5vw;
  margin-bottom: 1.5vw;
  color: #555;
}

.requirement i {
  width: 5vw;
  color: #666;
}

.level-privileges {
  padding-top: 2vw;
  border-top: 1px dashed #ddd;
}

.privilege-item {
  display: flex;
  align-items: center;
  font-size: 3.5vw;
  color: #555;
  margin-bottom: 1vw;
}

.privilege-item i {
  width: 5vw;
  color: #ff9800;
}

.rule-notes {
  list-style: none;
  padding: 0;
}

.rule-notes li {
  font-size: 3.5vw;
  color: #666;
  margin-bottom: 2vw;
  padding-left: 5vw;
  position: relative;
}

.rule-notes li:before {
  content: '•';
  position: absolute;
  left: 2vw;
  color: #ff9800;
  font-size: 4vw;
}

.vip-rules-dialog .dialog-footer {
  padding: 4vw;
  border-top: 1px solid #eee;
  display: flex;
  justify-content: flex-end;
}

.confirm-btn {
  padding: 2.5vw 6vw;
  background-color: #ff9800;
  color: white;
  border: none;
  border-radius: 1vw;
  font-size: 4vw;
  cursor: pointer;
}

.confirm-btn:hover {
  background-color: #f57c00;
}

/****************** 底部菜单部分 ******************/
/*.footer {
  width: 100%;
  height: 14vw;
  border-top: solid 1px #ddd;
  background-color: #fff;
  position: fixed;
  left: 0;
  bottom: 0;
  display: flex;
  justify-content: space-around;
  align-items: center;
}

.footer li {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: #999;
  user-select: none;
  cursor: pointer;
}

.footer li p {
  font-size: 2.8vw;
}

 .footer li i {
  font-size: 5vw;
}*/
</style>